package bbs

import (
    "fmt"
    "utils/util"
    "utils/mgo"
    "utils/web"
    "strconv"
	"time"
)

var tpl *util.Thtml   //模板变量
var db  *mgo.Database  //配置数据库
var session *util.Session  //session变量

var cfg map[string]map[string]string  //配置变量
var CfgPort string   //配置端口
var cfgSleep   time.Duration = 60 * time.Second  //睡眠时间

//var dao Dao
var SysGroup map[int]GroupUserData  //群组
var SysUser  map[string]string //当前用户信息



/**
 * 初始化论坛信息
 *
 * author: indraw
 * date: 2012-12-07
 */
func init() {
    
    var err error

    //读取配置,r如果没有配置文件，启用安装程序
    cfg, err = util.NewConfig("bbs/config/bbs.conf")
    if err != nil {
        fmt.Println("Config Error:", err)
        return
    }
    fmt.Println("-load config:bbs.conf")
    CfgPort = cfg["system"]["port"]

        
    //链接数据库
	con, err := mgo.Dial(cfg["mongo"]["host"] + ":" + cfg["mongo"]["port"])
    if err != nil {
        fmt.Println("Mongodb Error:", err)
        return
    }
    con.SetMode(mgo.Monotonic, true)
	db = con.DB("gobbs")
    fmt.Println("-connect mongo:"+cfg["mongo"]["host"]+"")

    //初始化模板
    tpl = util.NewThtml("bbs/templates/")
    fmt.Println("-load template:"+tpl.Dir+"")
    tpl.Assign("Gobbs", cfg["bbs"])


    //获取论坛相关信息
    g := newGroupUser()
    util.TplGroup = make(map[int]string)
    SysGroup, util.TplGroup = g.topSys()

    go initServer()

}

/**
 * 初始化论坛信息(web,session,),判断权限等
 *
 * author: indraw
 * date: 2013-02-07
 */
func initApp(ctx *web.Context) {
    
    tpl.Assign("BbsTitle", cfg["bbs"]["title"])

	ctx.Server.Config.CookieSecret = "gobbs-indraw"
	session = util.NewSession(ctx, util.NewMongoStore(cfg["mongo"]["host"] + ":" + cfg["mongo"]["port"]));

	//获取session
	SessUserID,_ := session.Get("userid")
	//fmt.Printf("sess userid %s\n",SessUserID)
	if SessUserID == ""{
		session.Set("userid","")
		
	}
	
	SessUserName,_ := session.Get("username")
	SessUserGroup,_ := session.Get("groupid")
	CheckIsAdmin,_ := strconv.Atoi(SessUserGroup)

    tpl.Assign("SessUserID", SessUserID)
    tpl.Assign("SessUserName", SessUserName)
    
    //赋值全局变量
    SysUser = make(map[string]string)
    SysUser["username"] = SessUserName
    SysUser["userid"] = SessUserID
    SysUser["groupid"] = SessUserGroup

    //判断是管理员，还是版主
    if CheckIsAdmin > 0 && CheckIsAdmin < 4{
        tpl.Assign("CheckIsAdmin", 1)
        
        SysUser["isadmin"] = "1"

    }else{
        tpl.Assign("CheckIsAdmin", 0)
        
        SysUser["isadmin"] = "0"

    }

    //赋值上一页地址
    tpl.Assign("UrlFrom", ctx.Request.Referer())

    

}

/**
 * 论坛后台定时执行程序
 *
 * author: indraw
 * date: 2013-03-07
 */
func initServer() {
    
    //执行一些程序
    i := 1
    for {
		
		//删除过期在线
		online :=  newOnline()
		online.deleteByTime()
		
		//
        
		fmt.Printf("-start server %d\n",i)
        //睡眠操作
        time.Sleep( cfgSleep )
        i++
    }

}

//w http.ResponseWriter, req *http.Request
func CheckPic(ctx *web.Context) {
	d := make([]byte, 4)
	s := util.NewLen(4)
	ss := ""
	d = []byte(s)
	for v := range d {
		d[v] %= 10
		ss += strconv.FormatInt(int64(d[v]), 32)
	}
	ctx.ResponseWriter.Header().Set("Content-Type", "image/png")
	util.NewImage(d, 100, 40).WriteTo(ctx.ResponseWriter)
	
    session.Set("pic",ss)
    //return ss
}







